<template>
    <div>
        <el-breadcrumb
            separator-class="el-icon-arrow-right"
            class="breadcrumb-base"
            style="line-height: 30px;"
        >
            <el-breadcrumb-item>
                <i class="el-icon-unlock"></i>
                权限设置
            </el-breadcrumb-item>
        </el-breadcrumb>

        <div class="main-container">
            <el-row>
                <el-button
                    @click="roleDialogOpen(-1)"
                    type="primary"
                    size="mini"
                    style="float: right"
                >新增角色
                </el-button>
            </el-row>
            <el-row style="margin-top: 10px;">
                <base-table
                    ref="rolesTable"
                    :data="rolesTable.data"
                    :header="rolesTable.header"
                    :pageInfo="rolesTable.pageInfo"
                    :pageSizes="[10, 15, 20]"
                    :selected="false"
                    @handleClick="rolesTableButtonClick"
                >
                </base-table>
            </el-row>
        </div>

        <el-dialog
            :visible.sync="roleDialog.visible"
            :title="roleDialog.title"
            :close-on-click-modal="false"
            :modal-append-to-body="false"
            append-to-body
            width="40%"
        >
            <el-form
                ref="roleDialogForm"
                :model="roleDialogForm"
                label-width="180px"
                :rules="roleDialogFormRules"
            >
                <el-form-item
                    label="名称"
                    prop="name"
                >
                    <el-input
                        v-model="roleDialogForm.name"
                        placeholder="请输入角色名称"
                        class="input-form"
                        size="mini"
                    ></el-input>
                </el-form-item>
                <el-form-item label="备注">
                    <el-input
                        v-model="roleDialogForm.description"
                        placeholder="请输入角色备注"
                        class="input-form"
                        size="mini"
                    ></el-input>
                </el-form-item>
                <el-form-item
                    label="是否为院内角色"
                    prop="isOuter"
                >
                    <el-radio
                        v-model="roleDialogForm.isOuter"
                        label="0"
                        size="mini"
                        :disabled="radioDisabled"
                    >是
                    </el-radio>
                    <el-radio
                        v-model="roleDialogForm.isOuter"
                        label="1"
                        size="mini"
                        :disabled="radioDisabled"
                    >否
                    </el-radio>
                </el-form-item>
            </el-form>
            <span
                slot="footer"
                class="dialog-footer"
                style="text-align: right;"
            >
                <el-button
                    @click="roleDialogCommit"
                    type="primary"
                    size="mini"
                >提交</el-button>
                <el-button
                    @click="roleDialog.visible = false"
                    size="mini"
                >关闭</el-button>
            </span>
        </el-dialog>
        <el-dialog
            :close-on-click-modal="false"
            title="权限设置"
            :visible.sync="authManageDialogVisible"
            width="50%"
            :before-close="authHandleClose"
        >
            <div v-if="radioDisabled == false">
                <el-card
                    class="box-card"
                    :body-style="{padding: '5px'}"
                    v-for=" (card, index) in permissionList"
                    :key="index"
                >
                    <div
                        slot="header"
                        class="clearfix"
                    >
                        <span>{{ card.name }}</span>
                        <el-checkbox
                            class="check-box-style"
                            v-model="card.checked"
                            @change="handleChoose(card, index)"
                        >全选
                        </el-checkbox>
                    </div>
                    <div class="tag-style">
                        <el-tag
                            size="mini"
                            style="margin-right: 5px;margin-top: 3px;cursor: pointer"
                            v-for="(tag, indexTag) in card.list"
                            :key="indexTag"
                            @click="chooseAuth(tag, index, indexTag)"
                            :type="tag.type"
                        >
                            {{ tag.name }}
                        </el-tag>
                    </div>
                </el-card>
            </div>
            <div v-else>
                <el-card
                    class="box-card"
                    :body-style="{padding: '5px'}"
                    v-for=" (card, index) in outerPermissionList"
                    :key="card.name"
                >
                    <div
                        slot="header"
                        class="clearfix"
                    >
                        <span>{{ card.name }}</span>
                        <el-checkbox
                            class="check-box-style"
                            v-model="card.checked"
                            @change="handleChooseOuter(card, index)"
                        >全选
                        </el-checkbox>
                    </div>
                    <div class="tag-style">
                        <el-tag
                            size="mini"
                            v-for="(tag, indexTag) in card.list"
                            :key="indexTag"
                            @click="chooseAuthOuter(tag, index, indexTag)"
                            :type="tag.type"
                        >
                            {{ tag.name }}
                        </el-tag>
                    </div>
                </el-card>
            </div>
            <span
                slot="footer"
                class="dialog-footer"
            >
                <el-button
                    type="primary"
                    size="mini"
                    @click="changeAuth"
                >确 定</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
import BaseTable from '@templates/components/BaseTable';
import _ from 'lodash';

export default {
    name: 'InstitutionPermissions',
    components: {
        BaseTable,
    },
    data() {
        const checkName = (rule, value, callback) => {
            if (!value) {
                callback(new Error(' '));
            } else {
                callback();
            }
        };
        return {
            nowRow: {},
            radioDisabled: false,
            authManageDialogVisible: false,
            innerHospitalConsultationAuthList: [],
            outOfHospitalConsultationAuthList: [],
            personAuthList: [],
            platformManagementAuthList: [],
            institutionalManagementAuthList: [],
            rolesTable: {
                data: [],
                header: [
                    {
                        prop: 'name',
                        label: '操作',
                        fixed: true,
                        width: '200',
                        isRender: true,
                        render: (h, params) => {
                            const _vm = this;
                            const props = {
                                type: 'text',
                                disabled: false,
                                size: 'small',
                                circle: 'circle',
                            };
                            const staticStyle = {
                                margin: '0 5px',
                            };
                            return h('div', [
                                h('span', [
                                    h(
                                        'el-button',
                                        {
                                            props: {
                                                ...props,
                                                disabled: params.row.id === 1,
                                            },
                                            on: {
                                                click: function ($event) {
                                                    return _vm.rolesEdit(
                                                        params.row
                                                    );
                                                },
                                            },
                                            staticStyle: { ...staticStyle },
                                        },
                                        '编辑'
                                    ),
                                ]),
                                h('span', [
                                    h(
                                        'el-button',
                                        {
                                            props: {
                                                ...props,
                                            },
                                            on: {
                                                click: function ($event) {
                                                    return _vm.rolesManagement(
                                                        params.row
                                                    );
                                                },
                                            },
                                            staticStyle: { ...staticStyle },
                                        },
                                        '权限设置'
                                    ),
                                ]),
                                h('span', [
                                    h(
                                        'el-button',
                                        {
                                            props: {
                                                ...props,
                                                disabled: params.row.id === 1,
                                            },
                                            on: {
                                                click: function ($event) {
                                                    return _vm.rolesDelete(
                                                        params.row
                                                    );
                                                },
                                            },
                                            staticStyle: {
                                                ...staticStyle,
                                                color:
                                                    params.row.id === 1
                                                        ? ''
                                                        : 'red',
                                            },
                                        },
                                        '删除'
                                    ),
                                ]),
                            ]);
                        },
                    },
                    {
                        label: '名称',
                        prop: 'name',
                        width: '160',
                    },
                    {
                        label: '是否为院内角色',
                        prop: 'isOuter',
                        width: '160',
                    },
                    {
                        label: '权限',
                        prop: 'permissionString',
                        width: '600',
                    },
                    {
                        label: '备注',
                        prop: 'description',
                    },
                ],
                operation: [
                    {
                        label: '编辑',
                        functionKey: 'rolesEdit',
                    },
                    {
                        label: '权限设置',
                        functionKey: 'rolesManagement',
                    },
                    {
                        label: '删除',
                        color: 'red',
                        functionKey: 'rolesDelete',
                    },
                ],
                pageInfo: {
                    hide: true,
                    page: 1,
                    size: 99,
                    total: 0,
                },
            },
            roleDialog: {
                visible: false,
                commitMethod: '',
                title: '',
            },
            roleDialogForm: {},
            roleDialogFormRules: {
                name: [
                    {
                        required: true,
                        message: ' ',
                        validator: checkName,
                        trigger: 'blur',
                    },
                ],
                isOuter: [
                    {
                        required: true,
                        message: ' ',
                        validator: checkName,
                        trigger: 'blur',
                    },
                ],
            },
            permissionList: [],
            innerPermissionList: [],
            outerPermissionList: [],
        };
    },
    mounted() {
        this.rolesTableDataRequest();
        this.permissionRequest();
    },
    methods: {
        prepareForm(index) {
            if (index < 0) {
                this.roleDialog.title = '新增角色';
                this.roleDialog.commitMethod = 'POST';

                delete this.roleDialogForm.id;
            } else {
                this.roleDialog.title = '编辑角色';
                this.roleDialog.commitMethod = 'PUT';

                Object.keys(this.roleDialogForm).forEach((key) => {
                    console.log('indexandkey', index, key);
                    if (key === 'isOuter') {
                        if (this.rolesTable.data[index - 1].isOuter === '是') {
                            console.log('happened1');
                            this.roleDialogForm.isOuter = '0';
                            this.radioDisabled = false;
                        } else {
                            console.log('happened2');
                            this.roleDialogForm.isOuter = '1';
                            this.radioDisabled = true;
                        }
                    } else {
                        this.roleDialogForm[key] =
                            this.rolesTable.data[index - 1][key];
                    }
                });
            }
        },
        roleDialogOpen(index) {
            this.roleDialogForm = {
                id: 0,
                name: '',
                description: '',
                permissions: [],
                isOuter: '0',
            };
            this.prepareForm(index);

            this.roleDialog.visible = true;
        },
        async roleDialogDelete(id) {
            await this.$axios({
                // 详见 axios 请求配置项
                method: 'DELETE',
                url: `/PROXY-Remote/roles/${id}`,
            }).then((res) => {
                // 请求失败
                if (res.data.code === 200) {
                    // 请求成功
                    this.$message.success(`删除成功`);
                    this.rolesTableDataRequest();
                    this.requestDictionaryInfo();
                } else {
                    this.$message.warning(res.data.message);
                }
            });
        },
        async rolePermissionCommit() {
            console.log('happend-http');
            await this.$axios({
                // 详见 axios 请求配置项
                method: 'PUT',
                url: '/PROXY-Remote/roles',
                data: this.roleDialogForm,
            }).then((res) => {
                // 请求失败
                console.log('happend-http-end');
                if (res.data.code !== 200) {
                    throw new Error(res.data);
                }

                // 请求成功
                this.$message.success(`${this.roleDialog.title}成功`);

                this.roleDialog.visible = false;
                this.rolesTableDataRequest();
                this.requestDictionaryInfo();
            });
        },
        roleDialogCommit() {
            this.$refs.roleDialogForm.validate(async (valid) => {
                if (valid) {
                    await this.$axios({
                        // 详见 axios 请求配置项
                        method: this.roleDialog.commitMethod,
                        url: '/PROXY-Remote/roles',
                        data: this.roleDialogForm,
                    }).then((res) => {
                        // 请求失败
                        if (res.data.code !== 200) {
                            throw new Error(res.data);
                        }

                        // 请求成功
                        this.$message.success(`${this.roleDialog.title}成功`);

                        this.roleDialog.visible = false;
                        this.rolesTableDataRequest();
                        this.requestDictionaryInfo();
                    });
                } else {
                    this.$message.warning('请输入必填项');
                }
            });
        },
        rolesTableButtonClick(functionKey, row) {
            // console.log('this[functionKey](row);', functionKey, row);
            this[functionKey](row);
        },
        async rolesTableDataRequest() {
            await this.$axios({
                // 详见 axios 请求配置项
                method: 'GET',
                url: '/PROXY-Remote/roles',
            }).then((res) => {
                // 请求失败
                if (res.data.code !== 200) {
                    throw new Error(res.data);
                }
                // 请求成功
                const result = res.data;
                this.rolesTable.data = [];
                this.rolesTable.pageInfo.total = result.data.length;
                result.data.forEach((t) => {
                    const permission = t;
                    permission.permissionString = '';
                    t.permissions.forEach((item) => {
                        permission.permissionString += `${item.name}  `;
                    });

                    this.rolesTable.data.push(permission);
                });
                for (let i = 0; i < this.rolesTable.data.length; i++) {
                    if (this.rolesTable.data[i].isOuter === 0) {
                        this.rolesTable.data[i].isOuter = '是';
                    } else {
                        this.rolesTable.data[i].isOuter = '否';
                    }
                    this.rolesTable.data[i].index = i + 1;
                }
            });
            console.log('rolesTable', this.rolesTable.data);
        },
        async permissionRequest() {
            await this.$axios({
                // 详见 axios 请求配置项
                method: 'GET',
                url: '/PROXY-Remote/permissions?page=0&size=100',
            }).then((res) => {
                // 请求失败
                if (res.data.code !== 200) {
                    throw new Error(res.data);
                }

                // 请求成功
                const result = res.data.data;
                if (result) {
                    Object.keys(result).forEach((key) => {
                        const outerList = [];
                        const innerList = [];
                        console.log('permisssion-key', key);
                        result[key].forEach((item) => {
                            if (item.isOuter === 1) {
                                outerList.push(item);
                            }
                            innerList.push(item);
                        });
                        if (outerList.length > 0) {
                            this.outerPermissionList.push({
                                name: key,
                                checked: false,
                                list: outerList,
                            });
                        }
                        this.permissionList.push({
                            name: key,
                            checked: false,
                            list: innerList,
                        });
                    });
                }
            });
        },
        // rolesTableFunction(row) {
        //   console.log('rolesTableFunction', row);
        // },
        rolesEdit(row) {
            // console.log('edit-roles', row);
            // Object.keys(row).forEach((key) => {
            //   console.log('key', key);
            //   this.roleDialogForm[key] = row[key];
            // });
            this.roleDialogOpen(row.index);
        },
        rolesDelete(row) {
            this.$confirm(`删除 ${row.name} 角色, 是否继续?`, '角色删除', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning',
            }).then(() => {
                this.roleDialogDelete(row.id);
            });
        },
        rolesManagement(row) {
            console.log('Management-roles', row);
            const permissionSet = new Set();
            if (row.permissions.length > 0) {
                row.permissions.forEach((item) => {
                    permissionSet.add(item.id);
                });
            }
            console.log('permissionSet', permissionSet);
            if (row.isOuter === '是') {
                this.radioDisabled = false;
                for (let init = 0; init < this.permissionList.length; init++) {
                    let count = 0;
                    for (
                        let i = 0;
                        i < this.permissionList[init].list.length;
                        i++
                    ) {
                        if (
                            permissionSet.has(
                                this.permissionList[init].list[i].id
                            )
                        ) {
                            this.permissionList[init].list[i].type = 'success';
                            count += 1;
                        } else {
                            this.permissionList[init].list[i].type = 'info';
                        }
                    }
                    if (count === this.permissionList[init].list.length) {
                        this.permissionList[init].checked = true;
                    } else {
                        this.permissionList[init].checked = false;
                    }
                }
            } else {
                this.radioDisabled = true;
                for (
                    let init = 0;
                    init < this.outerPermissionList.length;
                    init++
                ) {
                    let count = 0;
                    for (
                        let i = 0;
                        i < this.outerPermissionList[init].list.length;
                        i++
                    ) {
                        if (
                            permissionSet.has(
                                this.outerPermissionList[init].list[i].id
                            )
                        ) {
                            this.outerPermissionList[init].list[i].type =
                                'success';
                            count += 1;
                        } else {
                            this.outerPermissionList[init].list[i].type =
                                'info';
                        }
                    }
                    if (count === this.outerPermissionList[init].list.length) {
                        this.outerPermissionList[init].checked = true;
                    } else {
                        this.outerPermissionList[init].checked = false;
                    }
                }
            }
            this.authManageDialogVisible = true;
            this.nowRow = row;
        },
        authHandleClose(done) {
            if (this.radioDisabled === false) {
                for (let init = 0; init < this.permissionList.length; init++) {
                    for (
                        let i = 0;
                        i < this.permissionList[init].list.length;
                        i++
                    ) {
                        this.permissionList[init].list[i].type = 'info';
                    }
                    this.permissionList[init].checked = false;
                }
            } else {
                this.radioDisabled = true;
                for (
                    let init = 0;
                    init < this.outerPermissionList.length;
                    init++
                ) {
                    for (
                        let i = 0;
                        i < this.outerPermissionList[init].list.length;
                        i++
                    ) {
                        this.outerPermissionList[init].list[i].type = 'info';
                    }
                    this.outerPermissionList[init].checked = false;
                }
            }
            done();
        },
        changeAuth() {
            let list = [];
            if (this.radioDisabled === false) {
                this.permissionList.forEach((item) => {
                    list = _.concat(list, item.list);
                });
            } else {
                this.outerPermissionList.forEach((item) => {
                    list = _.concat(list, item.list);
                });
            }
            const filterList = _.filter(list, (o) => o.type === 'success');
            console.log('filterList', filterList);
            const idList = [];
            filterList.forEach((item) => {
                idList.push(_.pick(item, 'id'));
            });
            console.log('filterList-idList', filterList, idList);
            // this.roleDialogForm.permissions = idList;
            // this.roleDialogForm.id = this.nowRow.id;
            this.roleDialogForm = {
                id: this.nowRow.id,
                permissions: idList,
            };
            this.rolePermissionCommit();
            this.authManageDialogVisible = false;
        },
        chooseAuth(tag, index, indexTag) {
            console.log('index-indexTag', tag, index, indexTag);
            if (tag.type === 'info') {
                this.permissionList[index].list[indexTag].type = 'success';
                let filterList = _.clone(this.permissionList[index].list);
                filterList = _.filter(filterList, (o) => o.type === 'success');
                if (
                    filterList.length === this.permissionList[index].list.length
                ) {
                    this.permissionList[index].checked = true;
                }
            } else {
                this.permissionList[index].list[indexTag].type = 'info';
                console.log('happened');
                this.permissionList[index].checked = false;
            }
            this.$forceUpdate();
        },
        chooseAuthOuter(tag, index, indexTag) {
            console.log('tag', tag);
            if (tag.type === 'info') {
                this.outerPermissionList[index].list[indexTag].type = 'success';
                let filterList = _.clone(this.permissionList[index].list);
                filterList = _.filter(
                    this.outerPermissionList[index].list,
                    (o) => o.type === 'success'
                );
                if (
                    filterList.length ===
                    this.outerPermissionList[index].list.length
                ) {
                    this.outerPermissionList[index].checked = true;
                }
            } else {
                this.outerPermissionList[index].list[indexTag].type = 'info';
                this.outerPermissionList[index].checked = false;
            }
            this.$forceUpdate();
        },
        handleChoose(card, index) {
            if (!card.checked === false) {
                this.permissionList[index].checked = true;
                for (
                    let init = 0;
                    init < this.permissionList[index].list.length;
                    init++
                ) {
                    this.permissionList[index].list[init].type = 'success';
                }
            } else {
                console.log('happened-true', index);
                this.permissionList[index].checked = false;
                for (
                    let init = 0;
                    init < this.permissionList[index].list.length;
                    init++
                ) {
                    this.permissionList[index].list[init].type = 'info';
                }
            }
            this.$forceUpdate();
        },
        handleChooseOuter(card, index) {
            console.log('card', card);
            if (card.checked === false) {
                this.outerPermissionList[index].checked = true;
                for (
                    let init = 0;
                    init < this.outerPermissionList[index].list.length;
                    init++
                ) {
                    this.outerPermissionList[index].list[init].type = 'success';
                }
            } else {
                this.outerPermissionList[index].checked = false;
                for (
                    let init = 0;
                    init < this.outerPermissionList[index].list.length;
                    init++
                ) {
                    this.outerPermissionList[index].list[init].type = 'info';
                }
            }
        },
    },
};
</script>

<style scoped>
.tag-style {
    margin-left: 16px;
}
</style>
